<template>
  <a-row :gutter="[16, 16]">
    <!-- 图片展示区 -->
    <a-col :sm="24" :md="16" :xl="18">
      <a-card title="图片预览">
        <a-image
          style="max-height: 600px; object-fit: contain"
          :src="picture.url"
        />
      </a-card>
    </a-col>
    <!-- 图片信息区 -->
    <a-col :sm="24" :md="8" :xl="6">
      <a-card title="图片信息">
        <a-descriptions :column="1">
          <a-descriptions-item label="作者">
            <a-space>
              <a-avatar :size="24" :src="picture.user?.userAvatar" />
              <div>{{ picture.user?.userName }}</div>
            </a-space>
          </a-descriptions-item>
          <a-descriptions-item label="名称">
            {{ picture.name ?? '未命名' }}
          </a-descriptions-item>
          <a-descriptions-item label="简介">
            {{ picture.introduction ?? '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="分类">
            {{ picture.category ?? '默认' }}
          </a-descriptions-item>
          <a-descriptions-item label="标签">
            <a-tag v-for="tag in picture.tags" :key="tag">
              {{ tag }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="格式">
            {{ picture.picFormat ?? '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="宽度">
            {{ picture.picWidth ?? '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="高度">
            {{ picture.picHeight ?? '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="宽高比">
            {{ picture.picScale ?? '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="大小">
            {{ formatSize(picture.picSize) }}
          </a-descriptions-item>
          <a-descriptions-item label="审核状态" v-if="canReview">
            {{ reviewStatus === 2 ? '审核拒绝' : '审核通过' }}
          </a-descriptions-item>
          <a-space wrap>
            <a-button type="primary" @click="doDownload" style="margin-right: 10px">
              免费下载
              <template #icon>
                <DownloadOutlined />
              </template>
            </a-button>

            <a-button v-if="canEdit" type="default" @click="doEdit" style="margin-right: 10px">
              编辑
              <template #icon>
                <EditOutlined />
              </template>
            </a-button>

            <a-button v-if="canEdit" danger @click="doDelete" style="margin-right: 10px">
              删除
              <template #icon>
                <DeleteOutlined />
              </template>
            </a-button>

            <a-button v-if="canReview" @click="reviewButtonClick" :danger="isDanger">
              {{ buttonText }}
              <template #icon>
                <ExclamationCircleOutlined />
              </template>
            </a-button>
          </a-space>
        </a-descriptions>
      </a-card>
    </a-col>
  </a-row>
  <a-modal v-model:open="open" title='审核确认' :confirm-loading="confirmLoading" @ok="handleOk" ok-text="确认"
           cancel-text="取消">
    <p>是否设置为审核不通过？</p>
  </a-modal>
</template>

<script setup lang="ts">

import {
  deletePictureUsingPost,
  doPictureReviewUsingPost,
  getPictureVoByIdUsingGet,
  getReviewStatusUsingPost
} from '@/api/pictureController'
import { computed, onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import { downloadImage, formatSize } from '@/utils'
import { DeleteOutlined, EditOutlined, DownloadOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/counter'
import router from '@/router'
import { PIC_REVIEW_STATUS_ENUM } from '@/constants/picture'

const props = defineProps<{
  id: string | number
}>()

const picture = ref<API.PictureVO>({})
const confirmLoading = ref<boolean>(false)
const open = ref<boolean>(false)
const canReview = ref<boolean>()
const reviewStatus = ref<number>()
const isDanger = ref<boolean>()
const buttonText = ref<string>()

// 获取图片详情
const fetchPictureDetail = async () => {
  try {
    const res = await getPictureVoByIdUsingGet({
      id: props.id
    })
    if (res.data.code === 0 && res.data.data) {
      picture.value = res.data.data
    } else {
      message.error('获取图片详情失败，' + res.data.message)
    }
  } catch (e: never) {
    message.error('获取图片详情失败：' + e.message)
  }
}

const loginUserStore = useLoginUserStore()
// 是否具有编辑权限
const canEdit = computed(() => {
  const loginUser = loginUserStore.loginUser
  // 未登录不可编辑
  if (!loginUser.id) {
    return false
  }
  // 仅本人或管理员可编辑
  const user = picture.value.user || {}
  return loginUser.id === user.id || loginUser.userRole === 'admin'
})

// 是否具有审核权限并获取审核状态
const checkReview = async () => {
  const loginUser = loginUserStore.loginUser
  if (loginUser.userRole === 'admin') {
    const res = await getReviewStatusUsingPost(props.id)
    reviewStatus.value = res.data.data
    canReview.value = true
  }
  if (reviewStatus.value === 1) {
    isDanger.value = true
    buttonText.value = '审核拒绝'
  } else {
    isDanger.value = false
    buttonText.value = '审核通过'
  }
}
// 根据点击按钮的样式判断是否需要弹出二次确认
const reviewButtonClick = () => {
  if (isDanger.value) {
    open.value = true
  } else {
    doReview(PIC_REVIEW_STATUS_ENUM.PASS)
  }
}

// 二次确认的确认事件
const handleOk = () => {
  confirmLoading.value = true
  doReview(PIC_REVIEW_STATUS_ENUM.REJECT)
}

// 审核
const doReview = async (reviewStatus: number) => {
  const reviewMessage = reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '管理员操作通过' : '管理员操作拒绝'
  const res = await doPictureReviewUsingPost({
    id: props.id,
    reviewStatus,
    reviewMessage
  })
  if (res.data.code === 0) {
    // 二次确认才需要关闭确认框
    if (isDanger.value){
      open.value = false
      confirmLoading.value = false
    }
    message.success('审核操作成功')
    // 刷新页面
    await fetchPictureDetail()
    await checkReview()
  } else {
    // 二次确认才需要关闭确认框
    if (isDanger.value){
      open.value = false
      confirmLoading.value = false
    }
    message.error('审核操作失败，' + res.data.message)
    // 刷新页面
    await fetchPictureDetail()
    await checkReview()
  }
}

// 编辑
const doEdit = () => {
  router.push({
    path: '/addPicture',
    query: {
      id: picture.value.id,
      spaceId: picture.value.spaceId
    }
  })
}

// 删除
const doDelete = async () => {
  const id = picture.value.id
  if (!id) {
    return
  }
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
  } else {
    message.error('删除失败')
  }
}

// 处理下载
const doDownload = () => {
  downloadImage(picture.value.url)
}


onMounted(() => {
  fetchPictureDetail()
  checkReview()
})

</script>

<style scoped>

</style>
